<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;
//use think\addons\Service;
//use think\Exception;

use think\Session;
use app\admin\model\vppz\App;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class HealthPackage extends Base
{
	protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;

   protected $searchFields = ['id','name'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\HealthPackage;
        $this->service_model = new \app\admin\model\vppz\HealthService;
        $this->relationmodel = new \app\admin\model\vppz\PackageService;
        $community_id = input('ids',0);
        $this->assign('community_id',$community_id);
        $admin = Session::get("admin");
        $this->assignconfig('community_id',$community_id);
        $this->assign('admin',$admin);
        $this->assign('lengths',array(
            1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36
        ));
        $services = $this->service_model->whereNull('deletetime')->select();
        $this->assign('services',$services);
    }
     public function __get($name)
    {
        return Session::get('admin.' . $name);
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $ids = input('ids');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['community'])
                    ->where($where)
                    ->where('community_id','=',$ids)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('community')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $result = false;
            try {
                $Note = $this->model->where(['name'=>$form['name']])->find();
                if(empty($Note) === FALSE){
					$this->error('套餐名称已存在，重试看看呢');
                }
                $this->model->startTrans();
                $opera = [];
                $Data = array(
                    'name'=>$form['name'],
                    'weigh'=>$form['weigh'],
                    'community_id'=>$form['community_id'],
                    'content'=>$form['content'],
                    'price'=>$form['price'],
                    'show_price'=>$form['show_price'],
                    'length'=>$form['length'],
                    'image'=>$form['image']??'/uploads/20250805/dcf7dcf08c32ea1561224873e4af5025.jpg',
                    'info'=>mb_substr($form['info'],0,100),
                    'notices'=>$form['notices'],
                );
                $this->model->save($Data);
                $package_id =$this->model->id;
                $opera[] = $package_id;
                if(!$package_id){
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                //重新绑定关系
                if(empty($form['service_id']) === FALSE){
                    foreach ($form['service_id'] as $k=>$v){
                        $relation = array(
                            'package_id'=>$package_id,
                            'service_id'=>$v,
                            'num'=>$form['num'][$k],
                            'price'=>$form['service_price'][$k],
                            'createtime'=>time(),
                            'updatetime'=>time(),
                            'duration'=>$form['duration'][$k],
                        );
                        $opera[] = $this->relationmodel->insert($relation);
                    }
                }

                if(\Tools::checkArrayResult($opera)){
                    $this->model->commit();
                    $this->success();
                }else{
                    $this->model->rollback();
                    $this->error('新增套餐失败');
                }
            } catch (ValidateException|PDOException|Exception $e) {
                $this->error($e->getMessage());
            }
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            //查询绑定的服务列表
            $services = $this->relationmodel->with(['healthservice'])->select();
//            $this->view->assign('services', $services);
            $row['services'] = $services;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        try {
            $Note = $this->model->where(['name'=>$form['name']])->find();
            if(empty($Note) === FALSE && $Note['id'] != $ids){
                $this->error('套餐名称已存在，重试看看呢');
            }
            $this->model->startTrans();
            $opera = [];
            $Data = array(
                'name'=>$form['name'],
                    'weigh'=>$form['weigh'],
                    'content'=>$form['content'],
                    'price'=>$form['price'],
                    'updatetime'=>time(),
                    'show_price'=>$form['show_price'],
                    'length'=>$form['length'],
                    'image'=>$form['image']??'/uploads/20250805/dcf7dcf08c32ea1561224873e4af5025.jpg',
                    'info'=>mb_substr($form['info'],0,100),
                    'notices'=>$form['notices'],
            );
            $ret = $this->model->where(['id'=>$ids])->update($Data);
            if(!$ret){
                $this->error('服务器刚刚走神了，重试看看呢');
            }
            $opera[] = $ret;
            //删除之前绑定的所有服务
            $rela = $this->relationmodel->where([
                'package_id'=>$ids,
            ])->find();
            if(empty($rela)===false) {
                $opera[] = $this->relationmodel->where([
                    'package_id' => $ids,
                ])->delete();
            }
            //重新绑定关系
                if(empty($form['service_id']) === FALSE){
                    foreach ($form['service_id'] as $k=>$v){
                        $relation = array(
                            'package_id'=>$ids,
                            'service_id'=>$v,
                            'num'=>$form['num'][$k],
                            'price'=>$form['service_price'][$k],
                            'createtime'=>time(),
                            'updatetime'=>time(),
                            'duration'=>$form['duration'][$k],
                        );
                        $opera[] = $this->relationmodel->insert($relation);
                    }
                }
            if(\Tools::checkArrayResult($opera)){
                    $this->model->commit();
                    $this->success();
                }else{
                    $this->model->rollback();
                    $this->error('编辑套餐失败');
                }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }

}
